package com.sam.im.heiqun.uis.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.weixinAPPIDInfo;
import com.sam.im.heiqun.entities.weixinAPPIDbean;
import com.sam.im.heiqun.entities.weixinBean;
import com.sam.im.heiqun.entities.weixinQRData;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.pay.PayResult;
import com.sam.im.heiqun.pay.WXPay;
import com.sam.im.heiqun.uis.beans.RechargeOrderBean;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.EventBusType;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class PutForwardActivity extends BaseSwipeBackActivity implements TextWatcher {

    private static final String TAG = PutForwardActivity.class.getSimpleName();

    @BindView(R.id.money)
    EditText money;

    @BindView(R.id.next)
    Button next;

    @BindView(R.id.money_type)
    TextView moneyType;

    EditText message;
    PasswordEditText payPSD;
    private String type;
    private AlertDialog payDialog;

    PGService mPgService;
    String moneyStr;
    @Override
    public int getContentViewId() {
        return R.layout.activity_recharge;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.ofpresent);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPgService = PGService.getInstance();
        type = getIntent().getStringExtra("type");
        money.addTextChangedListener(this);
        next.setAlpha(0.5f);
        next.setEnabled(false);

        if ("0".equals(type)) {//微信支付
            moneyType.setText("￥");
        } else {
            moneyType.setText("￥");
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final Integer refresh) {
        if (refresh == EventBusType.RESULT_PAY_WX_SUCCESS) {
            finish();
        }
    }

    @OnClick({R.id.next})
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.next:
                doNext();
                break;

            case R.id.pay_commit:
                String pwd = payPSD.getText().toString().trim();
                if ("".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
                    validatePayPwd(pwd);
                }

                break;
            case R.id.pay_cancel:
                payDialog.dismiss();
                break;
            case R.id.pre_v_back:
                finish();
                break;
        }
    }

    private void doNext() {
        //final int moneyStr=Integer.parseInt(money.getText().toString());
        moneyStr = money.getText().toString().trim();
        if ("".equals(moneyStr)) {
            return;
        }

        String payInfo = ToolsUtils.getUser().getPayInfo();
        if (payInfo == null || payInfo.equals("")) {
            new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.tip_psw)).setMessage(getResources().getString(R.string.no_pay_psw)).setNegativeButton(getString(R.string.cancel), null).setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(PutForwardActivity.this, IdentityProvingActivity.class);
                    intent.putExtra("money", moneyStr);
                    intent.putExtra("type", type);
//                    showToast("type001="+type);
                    startActivity(intent);
                }
            }).create().show();
        } else {

            showPayDialog();




        }
    }

private void payment(){
 if ("1".equals(type)) {  // 海外支付
//                doOverSeasPay(moneyStr);
        double mmo1 = Double.parseDouble(moneyStr);
     int mmo= (int) (mmo1*100);
        setPayZFB("" + mmo);
    } else {//大陆支付
        double mmo1 = Double.parseDouble(moneyStr);
        int mmo= (int) (mmo1*100);

        if (mmo >= 0.01) {
            //  mmo = mmo * 100 ;
//                    login(mmo);
//                    setPayZH(""+mmo);//招行的支付对接，暂时隐藏
            setPayWX("" + mmo);
        } else {
            showToast(getResources().getString(R.string.not_0));
        }
    }
}
    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        payDialog = new AlertDialog.Builder(this).setView(dialog).create();
        payDialog.show();
        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(this);
        payCommit.setOnClickListener(this);
    }

    private void popupKeyboard(final PasswordEditText editText) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }

    /**
     * 验证支付密码
     *
     * @param pwd
     */
    private void validatePayPwd(String pwd) {
        String payPsd = MD5.MD532(pwd);
        mPgService.validatePayPwd(payPsd, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
//                    showToast("密码修改失败，请重试");
                new ToastUtils().showLongToast(getResources().getString(R.string.pay_psd_verify_defeat));
            }

            @Override
            public void onNext(String validateEntivity) {

                payment();
            }
        });
    }



    /*-----------------------------------------------招行开始------------------------------------------------------------*/

    private void setPayZH(String money) {
        Intent intentzh = new Intent(PutForwardActivity.this, RechargeZHWebViewActivity.class);
        intentzh.putExtra("money", money);
        startActivity(intentzh);
        hideProgress();
    }

    /*-----------------------------------------------招行结束------------------------------------------------------------*/

    /*-----------------------------------------------微信提现开始------------------------------------------------------------*/

    private void setPayWX(String  amount) {
/*
        SharedPreferences sharedPreferences= getSharedPreferences("TransferThePossessionOf11", Activity.MODE_PRIVATE);
    // 使用getString方法获得value，注意第2个参数是value的默认值
        String openid =sharedPreferences.getString("appId", "");*/
        //把需要传给后台的参数写成json然后加密传给后台，
        String userId=ToolsUtils.getMyUserId();
        com.alibaba.fastjson.JSONObject json = new JSONObject();
        json.put("userId", userId);
        json.put("amount", amount);

        String content = RequestRSAUtils.setRsaContent(json);
        //这里需要先去服务器请求支付订单信息，然后吊起微信支付

        PGService.getInstance().withdraw(content)
                .compose(this.<ValidateEntivity>applyProgress(""))
                .subscribe(new AbsAPICallback<ValidateEntivity>() {

                    @Override
                    public void onNext(ValidateEntivity ValidateEntivity) {
                        hideProgress();
                         String exStr = ValidateEntivity.getInfo();
                        try {
                        com.alibaba.fastjson.JSONObject json = JSON.parseObject(exStr);
                        //com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                        String code = json.getString("code");
                        if("1".equals(code)){
                            String info = json.getString("data");
                            showToast(info);
                        }
                        else {
                            com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                            String info = data.getString("info");
                            showToast(info);
                        }

                            finish();
                        }catch (Exception e){
                            showToast(ValidateEntivity.getInfo());
                            e.printStackTrace();
                        }
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        hideProgress();
                        String exStr = ex.getDisplayMessage();
                        try {
                            com.alibaba.fastjson.JSONObject json = JSON.parseObject(exStr);
                            //com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                            String code = json.getString("code");
                            if("1".equals(code)){
                                String info = json.getString("data");
                                showToast(info);
                            }
                            else {
                                com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                                String info = data.getString("info");
                                showToast(info);
                            }

                            finish();
                        }catch (Exception e){
                            showToast(ex.getDisplayMessage());
                            e.printStackTrace();
                        }

                    }
                });

    }

    /*-----------------------------------------------微信支付结束------------------------------------------------------------*/

    /*-----------------------------------------------支付宝提现开始------------------------------------------------------------*/
    private static final int SDK_PAY_FLAG = 1;

    private void setPayZFB(String amount) {
        String userId=ToolsUtils.getMyUserId();
        com.alibaba.fastjson.JSONObject json = new JSONObject();
        json.put("userId", userId);
        json.put("amount", amount);

        String content = RequestRSAUtils.setRsaContent(json);
        //这里需要先去服务器请求支付订单信息，然后吊起微信支付
        PGService.getInstance().alipayWithdraw(content)
                .compose(this.<ValidateEntivity>applyProgress(""))
                .subscribe(new AbsAPICallback<ValidateEntivity>() {


                    public void onNext(ValidateEntivity ValidateEntivity) {
                        hideProgress();
                        String exStr = ValidateEntivity.getInfo();
                        try {
                            com.alibaba.fastjson.JSONObject json = JSON.parseObject(exStr);
                            //com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                            String code = json.getString("code");
                            if("1".equals(code)){
                                String info = json.getString("data");
                                showToast(info);
                            }
                            else {
                                com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                                String info = data.getString("info");
                                showToast(info);
                            }

                            finish();
                        }catch (Exception e){
                            showToast(ValidateEntivity.getInfo());
                            e.printStackTrace();
                        }
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        hideProgress();
                        String exStr = ex.getDisplayMessage();
                        try {
                            com.alibaba.fastjson.JSONObject json = JSON.parseObject(exStr);
                            //com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                            String code = json.getString("code");
                            if("1".equals(code)){
                                String info = json.getString("data");
                                showToast(info);
                            }
                            else {
                                com.alibaba.fastjson.JSONObject data = json.getJSONObject("data");
                                String info = data.getString("info");
                                showToast(info);
                            }

                            finish();
                        }catch (Exception e){
                            showToast(ex.getDisplayMessage());
                            e.printStackTrace();
                        }

                    }
                });

    }




    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s == null || s.equals("")) {
            next.setAlpha(0.5f);
            next.setEnabled(false);
        } else {
            next.setAlpha(1f);
            next.setEnabled(true);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }



}
